package edu.ucla.cs.typecast.app.news;

import java.io.*;

import edu.ucla.cs.typecast.event.EventManager;
import edu.ucla.cs.typecast.event.EventSource;
import edu.ucla.cs.typecast.event.InvalidTypeException;

public class NewsSender {

	/**
	 * @param args
	 * @throws ClassNotFoundException
	 * @throws IllegalAccessException
	 * @throws InstantiationException
	 * @throws InvalidTypeException
	 */
	public static void main(String[] args) throws InterruptedException,
			IOException, InvalidTypeException, InstantiationException,
			IllegalAccessException, ClassNotFoundException {
		final EventSource source = EventManager.getInstance().getEventSource(
				NewsArticle.class);

		if (args.length < 1) {
			System.err
					.println("Usage: java [<parameters>] NewsSender <script>");
			System.exit(1);
		}

		ScriptParser p = new ScriptParser() {
			protected void send(Class cls, String content, Integer rate,
					Integer duration) {
				try {
					send2(cls, content, rate, duration);
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
			}

			protected void send2(Class cls, String content, Integer rate,
					Integer duration) throws InstantiationException,
					IllegalAccessException, InvalidTypeException, IOException {
				long startTime = System.currentTimeMillis();

				while (System.currentTimeMillis() - startTime < duration * 1000) {
					long startTime4CurrentIteration = System
							.currentTimeMillis();

					NewsArticle article = (NewsArticle) cls.newInstance();
					article.setContent(content);
					source.publishEvent(article);

					long stopTime4CurrentIteration = System.currentTimeMillis();
					long waitTime = Math.round(1000.0 / rate)
							- (stopTime4CurrentIteration - startTime4CurrentIteration);
					if (waitTime > 0) {
						try {
							Thread.sleep(waitTime);
						} catch (InterruptedException e) {
							//
						}
					}
				}

			}
		};

		p.parse(new FileReader(args[0]), false);
	}

}
